<!DOCTYPE html>
<html>
<head>
    <title>Configuration</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .user-section {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .username {
            color: #333;
            font-weight: bold;
        }
        .menu {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .menu a {
            text-decoration: none;
            color: #333;
            padding: 8px 16px;
            margin-right: 10px;
            border-radius: 4px;
        }
        .menu a.active {
            background-color: #4CAF50;
            color: white;
        }
        .menu a:hover {
            background-color: #ddd;
        }
        .config-container {
            background-color: #f5f5f5;
            padding: 20px;
            border-radius: 5px;
        }
        #configEditor {
            width: 100%;
            height: 300px;
            font-family: monospace;
            margin-bottom: 20px;
        }
        .button {
            background-color: #4CAF50;
            border: none;
            color: white;
            padding: 10px 20px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 4px 2px;
            cursor: pointer;
            border-radius: 4px;
        }
        .logout-button {
            background-color: #f44336;
        }
        .change-password-button {
            background-color: #2196F3;
        }
        .message {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }
        .success {
            background-color: #dff0d8;
            color: #3c763d;
        }
        .error {
            background-color: #f2dede;
            color: #a94442;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.4);
        }
        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 300px;
            border-radius: 5px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
        }
        .form-group input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        .close:hover {
            color: black;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>Configuration Settings</h1>
        <div class="user-section">
            <span class="username">{{ username }}</span>
            <button class="button change-password-button" onclick="openChangePasswordModal()">Change Password</button>
            <a href="{{ url_for('logout') }}" class="button logout-button">Logout</a>
        </div>
    </div>

    <div class="menu">
        <a href="{{ url_for('index') }}" class="active">Configuration</a>
        <a href="{{ url_for('logs') }}">Message Logs</a>
    </div>

    <div class="config-container">
        <textarea id="configEditor"></textarea>
        <button class="button" onclick="saveConfig()">Save Configuration</button>
    </div>
    <div id="message"></div>

    <!-- Change Password Modal -->
    <div id="changePasswordModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeChangePasswordModal()">&times;</span>
            <h2>Change Password</h2>
            <form id="changePasswordForm">
                <div class="form-group">
                    <label for="currentPassword">Current Password:</label>
                    <input type="password" id="currentPassword" required>
                </div>
                <div class="form-group">
                    <label for="newPassword">New Password:</label>
                    <input type="password" id="newPassword" required>
                </div>
                <div class="form-group">
                    <label for="confirmPassword">Confirm New Password:</label>
                    <input type="password" id="confirmPassword" required>
                </div>
                <button type="submit" class="button">Change Password</button>
            </form>
        </div>
    </div>

    <script>
        // Load configuration when page loads
        window.onload = function() {
            loadConfig();
        };

        function loadConfig() {
            fetch('/api/config')
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            window.location.href = '/login';
                            return;
                        }
                        throw new Error('Failed to load configuration');
                    }
                    return response.json();
                })
                .then(data => {
                    document.getElementById('configEditor').value = JSON.stringify(data, null, 2);
                })
                .catch(error => {
                    showMessage('Error loading configuration: ' + error, false);
                });
        }

        function saveConfig() {
            const configText = document.getElementById('configEditor').value;
            try {
                // Validate JSON format
                const config = JSON.parse(configText);
                
                fetch('/api/config', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: configText
                })
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            window.location.href = '/login';
                            return;
                        }
                        return response.json().then(data => {
                            throw new Error(data.error || 'Failed to save configuration');
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    showMessage('Configuration saved successfully!', true);
                })
                .catch(error => {
                    showMessage('Error saving configuration: ' + error, false);
                });
            } catch (e) {
                showMessage('Invalid JSON format: ' + e, false);
            }
        }

        function showMessage(message, isSuccess) {
            const messageDiv = document.getElementById('message');
            messageDiv.textContent = message;
            messageDiv.className = 'message ' + (isSuccess ? 'success' : 'error');
            messageDiv.scrollIntoView({ behavior: 'smooth' });
        }

        // Change Password Modal Functions
        function openChangePasswordModal() {
            document.getElementById('changePasswordModal').style.display = 'block';
        }

        function closeChangePasswordModal() {
            document.getElementById('changePasswordModal').style.display = 'none';
            document.getElementById('changePasswordForm').reset();
        }

        document.getElementById('changePasswordForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const currentPassword = document.getElementById('currentPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;

            if (newPassword !== confirmPassword) {
                showMessage('New passwords do not match', false);
                return;
            }

            fetch('/api/change-password', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    currentPassword: currentPassword,
                    newPassword: newPassword
                })
            })
            .then(response => {
                if (!response.ok) {
                    if (response.status === 401) {
                        window.location.href = '/login';
                        return;
                    }
                    return response.json().then(data => {
                        throw new Error(data.error || 'Failed to change password');
                    });
                }
                return response.json();
            })
            .then(data => {
                showMessage('Password changed successfully!', true);
                closeChangePasswordModal();
            })
            .catch(error => {
                showMessage('Error changing password: ' + error, false);
            });
        });
    </script>
</body>
</html>
